//
//  FQDUserRadar.m
//  FakeQDaily
//
//  Created by mewxiv on 9/26/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDUserRadar.h"
#import "FQDRadarView.h"
#import "FQDArticleFeedBaseViewController.h"
#import "FQDSimpleFeedCellItemProvider.h"
#import "FQDAccountManager.h"
#import "QDailyAPI.h"
#import "FQDRestModel.h"

#import "UIButton+WebCache.h"

@interface FQDUserRadar () <FQDRadarViewDelegate>

@property (nonatomic, strong) UIView *avatarBgView;
@property (nonatomic, strong) UIButton *avatarButton;
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *descLabel;
@property (nonatomic, strong) FQDRadarPolygonElement *outerElement;
@property (nonatomic, strong) FQDRadarPolygonElement *midElement;
@property (nonatomic, strong) FQDRadarPolygonElement *centerElement;
@property (nonatomic, strong) FQDRadarView *myRadar;

@end

@implementation FQDUserRadar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareRadarUI];
    }
    return self;
}

- (void)prepareRadarUI
{
    self.backgroundColor = [UIColor whiteColor];
    
    CGFloat viewWidth = self.bounds.size.width;
    CGFloat yOffset = 0;
    UIImage *radarBgImage = [UIImage imageNamed:@"iphoneRadarBg"];
    CGRect bgImageFrame = CGRectMake(0, 0, viewWidth, 200.0f);
    _bgImageView = [[UIImageView alloc] initWithFrame:bgImageFrame];
    _bgImageView.image = radarBgImage;
    _bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    _bgImageView.clipsToBounds = YES;
    _bgImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self addSubview:_bgImageView];
    
    yOffset = CGRectGetMaxY(bgImageFrame) + 10;
    
    CGRect titleFrame = CGRectMake(10, yOffset, viewWidth - 20, 20);
    _titleLabel = [[UILabel alloc] initWithFrame:titleFrame];
    _titleLabel.font = FQDBoldFontWithSize(16.0f);
    _titleLabel.textAlignment = NSTextAlignmentLeft;
    _titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self addSubview:_titleLabel];
    
    UITapGestureRecognizer *tapTitleLabelRecognizer =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleLabelTapped:)];
    [_titleLabel addGestureRecognizer:tapTitleLabelRecognizer];
    
    yOffset = CGRectGetMaxY(titleFrame) + 5;
    
    CGRect descFrame = CGRectMake(10, yOffset, viewWidth - 20, 40);
    _descLabel = [[UILabel alloc] initWithFrame:descFrame];
    _descLabel.font = FQDRegularFontWithSize(14.0f);
    _descLabel.textAlignment = NSTextAlignmentLeft;
    _descLabel.textColor = [UIColor colorWithWhite:0.4 alpha:1];
    _descLabel.numberOfLines = 2;
    _descLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self addSubview:_descLabel];
    
    UITapGestureRecognizer *tapDescLabelRecognizer =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(descLabelTapped:)];
    [_descLabel addGestureRecognizer:tapDescLabelRecognizer];
    
    [self setupRadar];
}

- (void)setupRadar
{
    FQDRadarPolygonElement *outerElement = [[FQDRadarPolygonElement alloc] init];
    outerElement.valueList = @[@1, @1, @1, @1, @1];
    outerElement.fillColor = [UIColor colorWithWhite:0 alpha:0.2];
    outerElement.drawDots = YES;
    outerElement.dotOuterColor = RGBA(255, 200, 31, 50);
    outerElement.dotInnerColor = RGBA(255, 200, 31, 178);
    self.outerElement = outerElement;
    
    FQDRadarPolygonElement *midElement = [[FQDRadarPolygonElement alloc] init];
    midElement.valueList = @[@0.9, @0.9, @0.9, @0.9, @0.9];
    midElement.fillColor = [UIColor colorWithWhite:0 alpha:0.3];
    self.midElement = midElement;
    
    FQDRadarPolygonElement *centerElement = [[FQDRadarPolygonElement alloc] init];
    centerElement.valueList = @[@0.54, @0.54, @0.54, @0.54, @0.54];
    centerElement.strokeColor = RGBA(255, 200, 32, 255);
    centerElement.fillColor = RGBA(255, 200, 32, 178);
    self.centerElement = centerElement;
    
    CGSize radarSize = CGSizeMake(self.bounds.size.width, 180.0f);
    CGRect radarFrame = CGRectMake(0, 20, radarSize.width, radarSize.height);
    _myRadar = [[FQDRadarView alloc] initWithFrame:radarFrame];
    _myRadar.backgroundColor = [UIColor clearColor];
    _myRadar.captionFontColor = [UIColor whiteColor];
    _myRadar.minValue = 0;
    _myRadar.maxValue = 1;
    _myRadar.polygonElements = @[outerElement, midElement, centerElement];
    _myRadar.captionList = @[@"开脑洞", @"技术宅", @"商业家", @"二次元", @"颜控"];
    _myRadar.delegate = self;
    [self addSubview:_myRadar];
    
    CGFloat avatarBgSize = 60.0f;
    CGRect avatarBgFrame = CGRectMake(0, 0, avatarBgSize, avatarBgSize);
    _avatarBgView = [[UIView alloc] initWithFrame:avatarBgFrame];
    _avatarBgView.layer.borderColor = FQDHighlightColorWithAlpha(26).CGColor;
    _avatarBgView.layer.borderWidth = 1.0f;
    _avatarBgView.layer.cornerRadius = avatarBgSize / 2;
    _avatarBgView.center = CGPointMake(radarSize.width / 2, radarSize.height / 2);
    _avatarBgView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |
    UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [_myRadar addSubview:_avatarBgView];
    
    CGFloat avatarSize = 55.0f;
    CGRect avatarFrame = CGRectMake(2.5, 2.5, avatarSize, avatarSize);
    UIImage *defaultAvatarImage = [UIImage imageNamed:@"avatar_default_icon_normal"];
    _avatarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _avatarButton.frame = avatarFrame;
    _avatarButton.layer.cornerRadius = avatarSize / 2;
    _avatarButton.clipsToBounds =  YES;
    _avatarButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |
    UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [_avatarButton setBackgroundImage:defaultAvatarImage forState:UIControlStateNormal];
    [_avatarButton addTarget:self action:@selector(avatarButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [_avatarBgView addSubview:_avatarButton];
}

- (void)updateRadar
{
    if (self.radarItems) {
        NSInteger itemsCount = [self.radarItems count];
        NSMutableArray *mutableValues = [NSMutableArray arrayWithCapacity:itemsCount];
        NSMutableArray *mutableCaptions = [NSMutableArray arrayWithCapacity:itemsCount];
        for (NSInteger i = 0; i < [self.radarItems count]; i++) {
            FQDRadarItem *radarItem = self.radarItems[i];
            [mutableValues addObject:@(radarItem.value)];
            [mutableCaptions addObject:radarItem.title];
        }
        self.centerElement.valueList = [mutableValues copy];
        self.myRadar.polygonElements = @[self.outerElement, self.midElement, self.centerElement];
        self.myRadar.captionList = [mutableCaptions copy];
    }
}

- (void)updateRadarUI
{
    FQDAccountManager *accountManager = [FQDAccountManager sharedManager];
    UIImage *defaultAvatarImage = [UIImage imageNamed:@"avatar_default_icon_normal"];
    if ([accountManager isLogined]) {
        NSInteger minIndex = 0;
        CGFloat minValue = CGFLOAT_MAX;
        if ([self.radarItems count] > 0) {
            for (NSInteger valueIndex = 0; valueIndex < [self.radarItems count]; valueIndex++) {
                FQDRadarItem *radarItem = self.radarItems[valueIndex];
                if (radarItem.value < minValue) {
                    minValue = radarItem.value;
                    minIndex = 0;
                }
            }
        }
        FQDRadarItem *minRadarItem = self.radarItems[minIndex];
        self.titleLabel.text = minRadarItem.excerpt;
        self.titleLabel.textAlignment = NSTextAlignmentLeft;
        self.titleLabel.userInteractionEnabled = NO;
        
        NSString *username = accountManager.currentUser.username;
        NSString *attribute = minRadarItem.title ? : @"";
        NSString *notEnoughString = [NSString stringWithFormat:@"%@，你的%@指数还不够哦", username, attribute];
        self.descLabel.text = notEnoughString;
        self.descLabel.userInteractionEnabled = NO;
        
        NSURL *avatarURL = [NSURL URLWithString:accountManager.currentUser.avatarURLString];
        [self.avatarButton sd_setBackgroundImageWithURL:avatarURL forState:UIControlStateNormal
                                       placeholderImage:defaultAvatarImage];
    } else {
        self.titleLabel.text = @"登录";
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.userInteractionEnabled = YES;
        
        self.descLabel.text = @"你都来好奇心了，怎么会不好奇？";
        self.descLabel.userInteractionEnabled = YES;
        [self.avatarButton setBackgroundImage:defaultAvatarImage forState:UIControlStateNormal];
    }
    
    [self updateRadar];
}

- (void)titleLabelTapped:(UIGestureRecognizer *)gr
{
    if (self.loginBlock) {
        id sender = gr.view;
        self.loginBlock(sender);
    }
}

- (void)descLabelTapped:(UIGestureRecognizer *)gr
{
    if (self.loginBlock) {
        id sender = gr.view;
        self.loginBlock(sender);
    }
}

- (void)avatarButtonTapped:(id)sender
{
    FQDAccountManager *accountManager = [FQDAccountManager sharedManager];
    if (![accountManager isLogined]) {
        self.loginBlock(sender);
    }
}

- (void)didTouchedCaption:(NSString *)caption atIndex:(NSInteger)index
{
    WeakSelf;
    FQDRadarItem *radarItem = self.radarItems[index];
    if (self.touchCaptionBlock && radarItem) {
        self.touchCaptionBlock(weakSelf.myRadar, radarItem);
    }
}

- (void)setRadarItems:(NSArray<FQDRadarItem *> *)radarItems
{
    _radarItems = radarItems;
    
    [self updateRadarUI];
}

@end
